package com.lizhe.jpa.controller;

import com.lizhe.jpa.dao.ArticleRepositoryPages;
import com.lizhe.jpa.model.AjaxResponse;
import com.lizhe.jpa.model.Article;
import com.lizhe.jpa.model.ArticleVO;
import com.lizhe.jpa.service.ArticleJPAService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 类描述:
 *
 * @author Administrator
 * @create 2021-10-27 21:43
 */
@RestController
@RequestMapping("/rest")
@Slf4j
public class JpaController {

    @Resource
    private ArticleJPAService articleJPAService;

    @Resource
    private ArticleRepositoryPages articleRepositoryPages;

    @PostMapping("/save")
    public AjaxResponse saveArticle(@RequestBody ArticleVO articleVO) {
        articleJPAService.saveArticle(articleVO);
        return AjaxResponse.success();
    }

    @PostMapping("/delete")
    public AjaxResponse delete(@RequestBody ArticleVO articleVO) {
        articleJPAService.deleteArticleById(articleVO.getId());
        return AjaxResponse.success();
    }


    @PostMapping("/one")
    public AjaxResponse findById(@RequestBody ArticleVO articleVO) {
        // return AjaxResponse.success(articleJPAService.findById(articleVO.getId()));

        // 根据名字生成SQL 方法
        return AjaxResponse.success(articleJPAService.findByAuthor(articleVO.getAuthor()));
    }

    @PostMapping("/list")
    public AjaxResponse getAllArticle() {
        List<Article> articles = articleJPAService.getAll();
        return AjaxResponse.success(articles);
    }


    // 测试分页 直接调dao下的查询了不写 service 了

    @PostMapping("/listPage")
    public AjaxResponse getAllByPager(@RequestBody ArticleVO articleVO) {
        // 只取前两条数据  并且 分页 +　排序，
        //  PageRequest.of 生成分页对象。
        PageRequest pageable = PageRequest.of(0, 2, Sort.by("createTime"));

        // 如果只排序的话
        // articleRepository.findAll(Sort.by("createTime"));
        //
        // articleRepository.findAll(Sort.by("author").ascending()
        //         .and(Sort.by("createTime").descending()));


        Page<Article> articlePage = articleRepositoryPages.findAll(pageable);

        long totalElements = articlePage.getTotalElements();
        int totalPages = articlePage.getTotalPages();
        log.info("总页数：" + totalPages);
        log.info("数据条数：" + totalElements);

        //将查询结果转换为List
        List<Article> articleList = articlePage.getContent();
        return AjaxResponse.success(articleList);
    }
}
